package com.imooc.dom4j;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class HrWriter {
	public void writeXml() throws Exception {
		
		//读取XML文件
		String file = "D:\\pro_software\\eclipse-workspace\\xml\\src\\com\\imooc\\dom4j\\hrTest.xml";
		//SAXReader类是读取XML文件的核心类，用于将XML解析后以树的形式保存到内存中
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);
			 Element root = document.getRootElement();
			 //用add方法，在根节点下面创建子节点
			 Element employee = root.addElement("employee");
			 //用addAttribute方法，在新加的employee节点中加入属性
			 employee.addAttribute("no", "3111");
			 //用add方法在新加的employee节点中加入name子节点
			 Element name = employee.addElement("name");
			 //为name节点设置文本
			 name.setText("老王");
			 //简化为一步，添加节点后，设置文本内容
			 employee.addElement("age").setText("20");
			 employee.addElement("salary").setText("3600");
			 Element department = employee.addElement("department");
			 department.addElement("dname").setText("人事部");
			 department.addElement("address").setText("XX大厦-B105");
			 //以上部分完成后只是在内存中构建了一个新的DOM树，
			 //但没有写入xml文件中，要想写入xml文件，还需要进行以下两步
			 Writer writer = new OutputStreamWriter(new FileOutputStream(file));//创建输出流
			 document.write(writer);
			 //输出流关闭
			 writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	
	}
	
	public static void main(String[] args) throws Exception {
		HrWriter hr = new HrWriter();
		hr.writeXml();
	}
}
